package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.task.ArticleHtmlTask;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.ArticleEnum;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-03
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService contentService;


    @Autowired
    private ArticleHtmlTask articleHtmlTask;


    /**
     * 新增正式发布文章
     *
     * @param dto
     * @return 发布后文章ID
     */
    @Override
    public Long saveArticle(ArticleDto dto) {
        //1.将提交dto参数封装ApArticle对象中
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);

        //2.判断操作类型是新增还是修改
        if (dto.getId() == null) {
            //2.1 新增操作
            //新增文章
            this.save(article);
            //新增文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(article.getId());
            apArticleContent.setContent(dto.getContent());
            contentService.save(apArticleContent);
        } else {
            //2.2 修改操作
            //修改文章
            this.updateById(article);
            //修改文章内容
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(ApArticleContent::getContent, dto.getContent());
            updateWrapper.eq(ApArticleContent::getArticleId, dto.getId());
            contentService.update(updateWrapper);
        }
        //TODO 异步 基于Freemarker产生文章静态页；将静态页文件上传到MinIO中
        try {
            articleHtmlTask.createAticleHtmlAndUpload(article.getId());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页失败：{}", e);
        }

        //3.返回文章ID
        return article.getId();
    }


    /**
     * 加载文章列表
     *
     * @param dto  入参查询条件
     * @param type 0：加载最新  1:加载更多
     * @return
     */
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int type) {
        //TODO 将来改为从分布式缓存Redis中获取，有Redis抗并发

        //1.构建分页对象
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        //2.构建查询条件
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        //2.1 设置频道查询条件
        if (ObjectUtils.isNotEmpty(dto.getChannelId())) {
            queryWrapper.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        //2.2 设置非删除 非下架状态
        queryWrapper.eq(ApArticle::getIsDown, false);
        queryWrapper.eq(ApArticle::getIsDelete, false);

        //2.3 设置时间条件
        if (type == ArticleEnum.ARTICLE_LOAD_LIST.getVal()) {
            //下拉获取最新
            queryWrapper.gt(ApArticle::getPublishTime, dto.getMaxTime());
        } else {
            //上拉获取更多
            queryWrapper.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        //2.4 根据发布时间进行倒序
        queryWrapper.orderByDesc(ApArticle::getPublishTime);

        //3.执行分页查询
        this.page(page, queryWrapper);

        //4.封装响应数据
        return new PageResponseResult(1L, dto.getSize(), page.getTotal(), page.getRecords());
    }


    /**
     * 查询文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //1.根据文章ID查询文章信息
        ApArticle article = this.getById(dto.getArticleId());
        if (article.getIsDown() || article.getIsDelete()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.根据文章ID查询文章内容信息
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = contentService.getOne(queryWrapper);

        //3.封装响应数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("config", article);
        result.put("content", content);
        return ResponseResult.okResult(result);
    }
}
